package com.wf.ew.sell.service.impl;

import com.wf.ew.common.JsonResult;
import com.wf.ew.common.PageResult;
import com.wf.ew.sell.biz.OutBillSonBiz;
import com.wf.ew.sell.model.OutBillSon;
import com.wf.ew.sell.model.SellSon;
import com.wf.ew.sell.service.OutBillSonService;
import com.wf.ew.system.model.User;
import com.wf.ew.sell.biz.OutBillBiz;
import com.wf.ew.sell.model.OutBill;
import com.wf.ew.sell.service.OutBillService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;

/**
 *
 * 数据服务层接口实现类
 * @author : Doman
 * @date : 2019-12-06 17:46:49
 * @version ：1.0
 */
@Service
public class OutBillServiceImpl implements OutBillService {

	@Autowired
	private OutBillBiz outBillBiz;
	@Autowired
	private OutBillSonBiz outBillSonBiz;
	@Autowired
	private OutBillSonService outBillSonService;

	@Override
	public String list(PageResult<T> page, OutBill outBill, User loginUser) {
		return outBillBiz.list(page,outBill,loginUser);
	}
	
	@Override
	public List<OutBill> list(OutBill outBill, User loginUser) {
		return outBillBiz.list(outBill,loginUser);
	}

	@Override
	public OutBill getById(OutBill outBill) {
		return outBillBiz.getById(outBill);
	}

	@Transactional
	@Override
	public JsonResult add(OutBill outBill, User loginUser) {
		KeyHolder key= outBillBiz.add(outBill, loginUser);
		int keyid = key.getKey().intValue();
		if (keyid>0) {
			return JsonResult.ok("添加成功").put("keyid",keyid);
		}
		return JsonResult.error("添加失败");
	}

	@Transactional
	@Override
	public JsonResult update(OutBill outBill, User loginUser) {
		if (outBillBiz.update(outBill, loginUser)) {
			return JsonResult.ok("修改成功");
		}
		return JsonResult.error("修改失败");
	}

	@Transactional
	@Override
	public JsonResult delete(OutBill outBill, User loginUser) {
		if (outBillBiz.delete(outBill, loginUser)) {
			return JsonResult.ok("删除成功");
		}
		return JsonResult.error("删除失败");
	}

	@Transactional
	@Override
	public JsonResult deleteOutAndSon(OutBill outBill, User loginUser) {
		OutBillSon outBillSon = null;
		String[] ids = outBill.getIds().split(", ");
		if (ids != null && ids.length > 0) {
			for (int j = 0; j < ids.length; j++) {
				outBillSon = new OutBillSon();
				outBillSon.setOutBillId(Integer.valueOf(ids[j]));
				List<OutBillSon> list = outBillSonBiz.list(outBillSon, loginUser);
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i ++) {
						outBillSon = list.get(i);
						outBillSon.setIds(outBillSon.getId());
						outBillSonService.delete(outBillSon, loginUser);
					}
				}
			}
		}
		if (outBillBiz.delete(outBill, loginUser)) {
			return JsonResult.ok("删除成功");
		}
		return JsonResult.error("删除失败");
	}
}
